$(function(){
	var map = null;
	var updateHandle = null;
	var onClickHandle = null;
	
	var parseXML = function(xml){
		if(window.DOMParser){
			var objDomParser = new DOMParser();
			return objDomParser.parseFromString(xml, "text/xml");
		}else{ // Internet Explorer
			var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async = "false";
			xmlDoc.loadXML(xml);
			return xmlDoc;
		}
	};
	
	var createMarker = function(map, point, user) {
		//Icone do celular:
		var cellphoneIcon = new GIcon();
		cellphoneIcon.image = "res/icon_cellphone.png";
		cellphoneIcon.shadow = "res/icon_cellphone_shadow.png";
		cellphoneIcon.iconSize = new GSize(40, 40);
		cellphoneIcon.shadowSize = new GSize(78, 40);
		cellphoneIcon.iconAnchor = new GPoint(17, 40);
		cellphoneIcon.infoWindowAnchor = new GPoint(17, 12);
		cellphoneIcon.infoShadowAnchor = new GPoint(14, 25);
		
		var marker = new GMarker(point, { icon: cellphoneIcon, title: user, clickable: false } );
		map.addOverlay(marker);
	};
	
	var drawCircle = function(map, lat, lng, radius, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity){
		var d2r = Math.PI/180;
		var r2d = 180/Math.PI;
		//Converting from kms to miles
		radius = radius/1.609344;
		var Clat = (radius/3963)*r2d;
		var Clng = Clat/Math.cos(lat*d2r);
		var Cpoints = [];
		for(var i = 0; i < 33; i++){
			var theta = Math.PI * (i/16);
			Cy = lat + (Clat * Math.sin(theta));
			Cx = lng + (Clng * Math.cos(theta));
			var P = new GPoint(Cx,Cy);
			Cpoints.push(P);
		}
		var polygon = new GPolygon(Cpoints, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity, {clickable: false});
		map.addOverlay(polygon);
	};

	var resetMemberUpdate = function(){
		if(updateHandle){
			clearInterval(updateHandle);
			updateHandle = null;
		}
	};
	
	var resetRadiusClickHandle = function(){
		if(onClickHandle){
			GEvent.removeListener(onClickHandle);
			onClickHandle = null;
		}
	};
	
	var hideRegisterForm = function(){
		var bot = $("#botaoCadastro button"); 
		if(bot.text() != "Cadastrar Nova Campanha"){
			bot.text('Cadastrar Nova Campanha');
			$('#cadCampanha form').get(0).reset();
			$('#cadCampanha').hide();
		}
	};
	
	var hideCampaignDescription = function(){
		$("#descCampanha").hide();
	};
	
	var resetCampaignSelection = function(){
		$('#lstCampanha li').removeClass('active');
		$("#descCampanha").hide();
	};
	
	var hideMap = function(){
		$('#map').hide();
	};
	
	var hideChat = function(){
		$('#chat').hide();
	};
	
	var resetInterface = function(){
		map.clearOverlays();
		resetMemberUpdate();
		resetRadiusClickHandle();
		hideCampaignDescription();
		hideRegisterForm();
		resetCampaignSelection();
		hideMap();
		hideChat();
	};
	
	//Inicializador do Google Maps
	if(GBrowserIsCompatible()){
		var map = new GMap2($("#map").get(0), { size: new GSize(400, 300) });
		map.setCenter(new GLatLng(-11.06629,-49.2334), 4);
		map.enableContinuousZoom();
		map.enableScrollWheelZoom();
	}
	//Destrutor do Google Maps
	$("body").unload(GUnload);

	//Requisitando as campanhas
	$.get(
		"/JoinUs-ApplicationServer/servlets/Campaign",
		{ auth: 0, action: "list" },
		function(data){
			//tratando erros na resposta da requisição
			if(data.length < 2){ return; }
			var status = data.substr(0, 2);
			if(status != "ok"){ return; }

			//pula o ok no início da requisição e adiciona o cabeçalho XML
			var xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + data.substring(3);

			xml = parseXML(xml);

			//Construindo a listagem de campanhas a partir do XML
			$(xml).find("Campaign").each(function(key, value){
				$("<li />").text($(this).find("name").text()).hover(
					function(){$(this).addClass('hover');},
					function(){$(this).removeClass('hover');}
				).click(function(){					
					var vetCoords = $(value).find("area").text().split(",");
					vetCoords[0] = parseFloat(vetCoords[0].substring(1)); //Lat
					vetCoords[1] = parseFloat(vetCoords[1].substring(-1)); //Lng
					vetCoords[2] = parseFloat(vetCoords[2]); //Radius
					
					var campCenter = new GLatLng(vetCoords[0], vetCoords[1]);
					var campRadius = parseFloat(vetCoords[2]);
					
					//Carrega os dados no div#descCampanha e mostra-o
					$("#descCampanha").find("h2")
						.text($(value).find("name").text())
					.end().find("div")
						.find("span:eq(1)")
							.text($(value).find("description").text())
						.end().find("span:eq(3)")
							.text($(value).find("area").text())
						.end().find("span:eq(5)")
							.text($(value).find("creation").text())
						.end().find("span:eq(7)")
							.text($(value).find("expiration").text())
						.end()
					.end();
					
					resetInterface();
					$(this).addClass('active');
					$("#map").show();
					$("#descCampanha").show();
					$("#chat").show();
					drawCircle(map, campCenter.lat(), campCenter.lng(), campRadius, "000000", 3, 1, "0000ff", 0.3);
					map.panTo(campCenter);				
					map.openInfoWindow(campCenter, $("<span />").addClass("aviso").text("Carregando Usuários...").get(0));

					//Carrega os usuários desta campanha
					$.get(
						"/JoinUs-ApplicationServer/servlets/Campaign",
						{ auth: 0, action: "users", idCampaign: $(value).find("idCampaign").text() },
						function(data){
							//tratando erros na resposta da requisição
							if(data.length < 2){ return; }
							var status = data.substr(0, 2);
							if(status != "ok"){ return; }

							//pula o ok no início da requisição e adiciona o cabeçalho XML
							var xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + data.substring(3);

							xml = parseXML(xml);

							resetMemberUpdate();
							updateHandle = setInterval(function(){
								//Requisitando a posição dos usuários
								$.ajax({
									url: "/JoinUs-LocationManager/Dispatcher?function=GetAllLocations",
									dataType: "xml",
									success: function(userMarkers){
										var lstUsers = [];

										map.clearOverlays();
										drawCircle(map, campCenter.lat(), campCenter.lng(), campRadius, "000000", 3, 1, "0000ff", 0.3);
										//Criando os marcadores dos usuários
										$(xml).find("Campaigner").each(function(key, value){
											var userLogin = $(value).find("login").text();
											var userMarker = $(userMarkers).find("marker[login=" + userLogin + "]");
	
											lstUsers.push($(userMarker).attr("name"));
											createMarker(map, new GLatLng(parseFloat(userMarker.attr("lat")), parseFloat(userMarker.attr("lng"))), userMarker.attr("name"));
										});
										map.closeInfoWindow();
										//Atualiza a descrição da campanha
										$("#descCampanha p:last").text(lstUsers.join(", "));
									}
								});
							}, 10000);
						}
					);
				}).appendTo("#lstCampanha");
			});
		}
	);
	
	$("#botCadastro").click(function(){		
		if($(this).text() == "Cadastrar Nova Campanha"){
			resetInterface();
			$(this).text('Cancelar Cadastro');
			$("#map").add("#cadCampanha").show();
			onClickHandle = GEvent.addListener(map, 'click', function(overlay, latlng){
				map.clearOverlays();
				drawCircle(map, latlng.lat(), latlng.lng(), $("#cadCampanha form input[name='numRaio']").val(), "000000", 3, 1, "0000ff", 0.3);
				$("#cadCampanha form input[name='coordPosicao']").val(latlng.lat().toString() + ", " + latlng.lng().toString());
			});
		}else{
			resetInterface();
			$(this).text('Cadastrar Nova Campanha');
			$('#cadCampanha form').get(0).reset();
		}
	});
});